Skip to main content

DSA Tips & Tricks - 2025 Edition

๐Ÿ”„ Array Utilitiesโ€‹

Swap Functionโ€‹

function swap(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
}

Reverse Arrayโ€‹

function reverseArray(arr) {
return arr.reverse();
}
// In-place reverse
function reverseInPlace(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
[arr[left], arr[right]] = [arr[right], arr[left]];
left++; right--;
}
}

Check for Duplicatesโ€‹

function hasDuplicates(arr) {
return new Set(arr).size !== arr.length;
}

Find Maximum/Minimumโ€‹

function findMax(arr) {
return Math.max(...arr);
}

function findMin(arr) {
return Math.min(...arr);
}

// For large arrays (avoid stack overflow)
function findMaxSafe(arr) {
return arr.reduce((max, curr) => Math.max(max, curr), -Infinity);
}

Sum of Elementsโ€‹

function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}

Generate Rangeโ€‹

function range(start, end) {
return Array.from({ length: end - start + 1 }, (_, i) => start + i);
}

๐Ÿ—บ๏ธ Matrix & 2D Array Operationsโ€‹

Creating Visited Array for 2D Matrixโ€‹

const rows = 3, cols = 3;
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));

Use Case: Track visited nodes in 2D grid traversals (BFS, DFS)

Traversing 2D Matrix - All Directionsโ€‹

const directions = [
[0, 1], // right
[1, 0], // down
[0, -1], // left
[-1, 0], // up
[1, 1], // down-right (diagonal)
[1, -1], // down-left (diagonal)
[-1, 1], // up-right (diagonal)
[-1, -1] // up-left (diagonal)
];

for (let [dr, dc] of directions) {
const newRow = row + dr;
const newCol = col + dc;
if (isValid(newRow, newCol, rows, cols)) {
// Process cell
}
}

Boundary Check for Matrixโ€‹

const isValid = (row, col, rows, cols) => {
return row >= 0 && row < rows && col >= 0 && col < cols;
};

DFS/BFS Queue for Matrixโ€‹

const queue = [[startRow, startCol]];
const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]];

while (queue.length) {
const [row, col] = queue.shift();

for (let [dr, dc] of directions) {
const newRow = row + dr;
const newCol = col + dc;
if (isValid(newRow, newCol, rows, cols) && !visited[newRow][newCol]) {
visited[newRow][newCol] = true;
queue.push([newRow, newCol]);
}
}
}

๐Ÿงฎ Dynamic Programming Arraysโ€‹

1D DP Arrayโ€‹

const n = 4;
const dp = Array(n).fill(0);
// [0, 0, 0, 0]

2D DP Arrayโ€‹

const rows = 3, cols = 3;
const dp = Array.from({ length: rows }, () => Array(cols).fill(0));

Use Case: Grid path problems, edit distance, longest common subsequence

3D DP Arrayโ€‹

const x = 2, y = 3, z = 4;
const dp = Array.from({ length: x }, () =>
Array.from({ length: y }, () => Array(z).fill(0))
);

๐Ÿ”ค String Utilitiesโ€‹

Alphanumeric Checkโ€‹

function isAlphanumeric(str) {
return /^[a-zA-Z0-9]+$/.test(str);
}

function isAlphanumericChar(char) {
return (('A' <= char && char <= 'Z') ||
('a' <= char && char <= 'z') ||
('0' <= char && char <= '9'));
}

Character Code Utilitiesโ€‹

// Convert char to number (a=0, b=1, ...)
const charToNum = (char) => char.charCodeAt(0) - 'a'.charCodeAt(0);

// Convert number to char (0=a, 1=b, ...)
const numToChar = (num) => String.fromCharCode(num + 'a'.charCodeAt(0));

String Frequency Mapโ€‹

function getFrequencyMap(str) {
const freq = {};
for (let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
return freq;
}

๐Ÿ”ข Mathematical Utilitiesโ€‹

GCD (Greatest Common Divisor)โ€‹

function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b);
}

LCM (Least Common Multiple)โ€‹

function lcm(a, b) {
return (a * b) / gcd(a, b);
}

Prime Number Checkโ€‹

function isPrime(n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;

for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) return false;
}
return true;
}

Power Function (Fast Exponentiation)โ€‹

function power(base, exp) {
if (exp === 0) return 1;
if (exp % 2 === 0) {
const half = power(base, exp / 2);
return half * half;
}
return base * power(base, exp - 1);
}

๐Ÿ“ Geometry Formulasโ€‹

Rectangle Areaโ€‹

const rectangleArea = (x1, y1, x2, y2) => Math.abs(x2 - x1) * Math.abs(y2 - y1);

Triangle Area (Coordinates)โ€‹

const triangleArea = (x1, y1, x2, y2, x3, y3) => {
return Math.abs(x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2)) / 2;
};

Distance Between Pointsโ€‹

const distance = (x1, y1, x2, y2) => {
return Math.sqrt((x2 - x1)**2 + (y2 - y1)**2);
};

๐ŸŒณ Tree Utilitiesโ€‹

Binary Tree Nodeโ€‹

class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}

Tree Traversalsโ€‹

// Inorder (Left, Root, Right)
function inorder(root, result = []) {
if (!root) return result;
inorder(root.left, result);
result.push(root.val);
inorder(root.right, result);
return result;
}

// Preorder (Root, Left, Right)
function preorder(root, result = []) {
if (!root) return result;
result.push(root.val);
preorder(root.left, result);
preorder(root.right, result);
return result;
}

// Level Order (BFS)
function levelOrder(root) {
if (!root) return [];
const queue = [root];
const result = [];

while (queue.length) {
const level = [];
const size = queue.length;

for (let i = 0; i < size; i++) {
const node = queue.shift();
level.push(node.val);

if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
result.push(level);
}
return result;
}

๐Ÿ”— Linked List Utilitiesโ€‹

ListNode Definitionโ€‹

class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}

Reverse Linked Listโ€‹

function reverseList(head) {
let prev = null;
let curr = head;

while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}

Find Middle of Linked Listโ€‹

function findMiddle(head) {
let slow = head;
let fast = head;

while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}

๐ŸŽฏ Two Pointers Techniquesโ€‹

Two Sum (Sorted Array)โ€‹

function twoSum(nums, target) {
let left = 0, right = nums.length - 1;

while (left < right) {
const sum = nums[left] + nums[right];
if (sum === target) return [left, right];
else if (sum < target) left++;
else right--;
}
return [-1, -1];
}

Remove Duplicatesโ€‹

function removeDuplicates(nums) {
let i = 0;
for (let j = 1; j < nums.length; j++) {
if (nums[j] !== nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}

๐ŸชŸ Sliding Window Patternsโ€‹

Fixed Size Windowโ€‹

function maxSumSubarray(arr, k) {
let maxSum = 0;
let windowSum = 0;

// Calculate sum of first window
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;

// Slide the window
for (let i = k; i < arr.length; i++) {
windowSum = windowSum - arr[i - k] + arr[i];
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}

Variable Size Windowโ€‹

function longestSubstringKDistinct(s, k) {
const map = new Map();
let left = 0, maxLen = 0;

for (let right = 0; right < s.length; right++) {
map.set(s[right], (map.get(s[right]) || 0) + 1);

while (map.size > k) {
map.set(s[left], map.get(s[left]) - 1);
if (map.get(s[left]) === 0) map.delete(s[left]);
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}

๐Ÿ” Binary Search Patternsโ€‹

function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}

Find First/Last Occurrenceโ€‹

function findFirst(arr, target) {
let left = 0, right = arr.length - 1, result = -1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
result = mid;
right = mid - 1; // Continue searching left
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}

๐ŸŽฒ Bit Manipulationโ€‹

Common Bit Operationsโ€‹

// Check if bit is set
const isBitSet = (num, i) => (num & (1 << i)) !== 0;

// Set bit
const setBit = (num, i) => num | (1 << i);

// Clear bit
const clearBit = (num, i) => num & ~(1 << i);

// Toggle bit
const toggleBit = (num, i) => num ^ (1 << i);

// Count set bits
const countSetBits = (num) => {
let count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
return count;
};

๐Ÿ—๏ธ Graph Utilitiesโ€‹

Graph Representationโ€‹

// Adjacency List
const graph = new Map();
graph.set(node, [neighbors]);

// Add edge
function addEdge(graph, u, v) {
if (!graph.has(u)) graph.set(u, []);
if (!graph.has(v)) graph.set(v, []);
graph.get(u).push(v);
graph.get(v).push(u); // For undirected graph
}

DFS Templateโ€‹

function dfs(graph, start, visited = new Set()) {
visited.add(start);

for (let neighbor of graph.get(start) || []) {
if (!visited.has(neighbor)) {
dfs(graph, neighbor, visited);
}
}
}

BFS Templateโ€‹

function bfs(graph, start) {
const queue = [start];
const visited = new Set([start]);

while (queue.length) {
const node = queue.shift();

for (let neighbor of graph.get(node) || []) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}

๐ŸŽฏ Common Patterns & Tricksโ€‹

Fast & Slow Pointers (Floyd's Cycle Detection)โ€‹

function hasCycle(head) {
let slow = head, fast = head;

while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}

Merge Intervalsโ€‹

function mergeIntervals(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const merged = [intervals[0]];

for (let i = 1; i < intervals.length; i++) {
const current = intervals[i];
const last = merged[merged.length - 1];

if (current[0] <= last[1]) {
last[1] = Math.max(last[1], current[1]);
} else {
merged.push(current);
}
}
return merged;
}

Topological Sort (Kahn's Algorithm)โ€‹

function topologicalSort(graph, indegree) {
const queue = [];
const result = [];

// Find all nodes with 0 indegree
for (let [node, degree] of indegree) {
if (degree === 0) queue.push(node);
}

while (queue.length) {
const node = queue.shift();
result.push(node);

for (let neighbor of graph.get(node) || []) {
indegree.set(neighbor, indegree.get(neighbor) - 1);
if (indegree.get(neighbor) === 0) {
queue.push(neighbor);
}
}
}
return result;
}

๐Ÿš€ Performance Tipsโ€‹

Avoid Array Methods in Loopsโ€‹

// โŒ Slow
for (let i = 0; i < arr.length; i++) { /* ... */ }

// โœ… Fast
const len = arr.length;
for (let i = 0; i < len; i++) { /* ... */ }

Use Map for O(1) Lookupsโ€‹

// โŒ O(n) lookup
const arr = [1, 2, 3, 4, 5];
if (arr.includes(target)) { /* ... */ }

// โœ… O(1) lookup
const set = new Set([1, 2, 3, 4, 5]);
if (set.has(target)) { /* ... */ }

Bitwise Operations for Even/Oddโ€‹

// โŒ Slower
if (num % 2 === 0) { /* even */ }

// โœ… Faster
if ((num & 1) === 0) { /* even */ }

๐Ÿ“š Essential Resourcesโ€‹